package de.pitkley.updater;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.Observable;
import java.util.Observer;

/*
 * Updater.java
 *
 * Created on 15.10.2011, 16:54:10
 */
/**
 *
 * @author pit
 */
public class Updater extends javax.swing.JFrame implements Observer {

    private static File wd = Util.getWorkingDirectory("jocabulary");
    private static File versionPath = new File(wd, "version");
    private static String currentVersion;
    private static String latestVersion;
    private static Download latestJar;

    private void startJocabulary() {
        try {
            String[] jarList = {"jocabulary"};
            URL[] urlList = new URL[jarList.length];

            for (int i = 0; i < jarList.length; i++) {
                urlList[i] = new File(wd, "bin" + File.separator + jarList[i] + ".jar").toURI().toURL();
            }

            URLClassLoader ucl = new URLClassLoader(urlList);
            Class<?> c = ucl.loadClass("de.pitkley.jocabulary.Jocabulary_Controller");
            Object joc = c.getConstructor().newInstance();
            this.setVisible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Creates new form Updater */
    public Updater() {
        checkVersions();

        initComponents();
        pbDownload.setMaximum(100);
        lblError.setVisible(false);

        if (currentVersion.equals("")) {
            lblCurrentVersion.setText("- Noch nicht vorhanden -");
            btnNo.setEnabled(false);
        } else {
            lblCurrentVersion.setText(currentVersion);
        }
        lblLatestVersion.setText(latestVersion);

        if (!updateAvailable()) {
            startJocabulary();
            return;
        }

        this.setVisible(true);
    }

    private static void checkVersions() {
        File dir = new File(Util.getWorkingDirectory("jocabulary"), "bin" + File.separator);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        latestVersion = getLatestVersion();
        currentVersion = readVersionFile(versionPath);
    }

    private static boolean updateAvailable() {
        return (!currentVersion.equals(latestVersion));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblCurrentVersion = new javax.swing.JLabel();
        lblLatestVersion = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        btnYes = new javax.swing.JButton();
        btnNo = new javax.swing.JButton();
        pbDownload = new javax.swing.JProgressBar();
        lblError = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Es ist eine neue Version von Jocabulary verfügbar!");

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Deine Version:");

        jLabel3.setText("Verfügbare Version:");

        jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 24));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Jocbulary - Updater");

        lblCurrentVersion.setText("jLabel5");

        lblLatestVersion.setForeground(new java.awt.Color(255, 0, 0));
        lblLatestVersion.setText("jLabel6");

        jLabel7.setFont(new java.awt.Font("Lucida Grande", 1, 18));
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("Update herunterladen?");

        btnYes.setText("Ja!");
        btnYes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnYesActionPerformed(evt);
            }
        });

        btnNo.setLabel("Nein.");
        btnNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNoActionPerformed(evt);
            }
        });

        lblError.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
        lblError.setForeground(new java.awt.Color(255, 0, 0));
        lblError.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblError.setText("Beim Herunterladen gab es ein Problem!");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, lblError, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, pbDownload, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(btnYes, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnNo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 177, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblLatestVersion, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                            .add(lblCurrentVersion, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(lblCurrentVersion))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(lblLatestVersion))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 31, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnYes)
                    .add(btnNo))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pbDownload, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(lblError, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 33, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        lblCurrentVersion.getAccessibleContext().setAccessibleName("lblCurrentVersion");
        lblLatestVersion.getAccessibleContext().setAccessibleName("lblLatestVersion");
        btnNo.getAccessibleContext().setAccessibleName("btnNo");

        getAccessibleContext().setAccessibleName("Jocabulary");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnYesActionPerformed
        btnYes.setEnabled(false);
        btnNo.setEnabled(false);
        try {
            downloadLatestVersion();
        } catch (MalformedURLException e) {
            lblError.setVisible(true);
        }
    }//GEN-LAST:event_btnYesActionPerformed

    private void btnNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNoActionPerformed
        startJocabulary();
    }//GEN-LAST:event_btnNoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Updater();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnNo;
    private javax.swing.JButton btnYes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel lblCurrentVersion;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblLatestVersion;
    private javax.swing.JProgressBar pbDownload;
    // End of variables declaration//GEN-END:variables

    private static String getLatestVersion() {
        String lv;
        try {
            String URLName = "http://jocabulary.pitkley.de/latestversion";
            URL openurl = new URL(URLName);
            URLConnection uc = openurl.openConnection();
            uc.setConnectTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            lv = in.readLine();
            in.close();
        } catch (IOException e) {
            lv = null;
        }

        return lv;
    }

    private static String readVersionFile(File f) {
        String version;
        try {
            DataInputStream dis = new DataInputStream(new FileInputStream(f));
            version = dis.readUTF();
            dis.close();

            return version;
        } catch (IOException ex) {
            version = "";
        }

        return version;
    }

    private static void writeVersionFile(File f, String version) {
        try {
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
            dos.writeUTF(version);
            dos.close();
        } catch (Exception ex) {
        }
    }

    private void downloadLatestVersion() throws MalformedURLException {
        latestJar = new Download(new URL("http://jocabulary.pitkley.de/download/jocabulary/" + latestVersion + "/jocabulary.jar"), wd.getAbsolutePath() + File.separator + "bin/");
        latestJar.addObserver(this);
        latestJar.start();
    }

    @Override
    public void update(Observable o, Object ob) {
        Download d = (Download) o;
        switch (d.getStatus()) {
            case Download.DOWNLOADING:
                pbDownload.setValue((int) d.getProgress());
                break;
            case Download.COMPLETE:
                writeVersionFile(versionPath, latestVersion);
                deleteOldData();
                startJocabulary();
                break;
            case Download.ERROR:
                lblError.setVisible(true);
                break;
            default:
                break;
        }
    }

    private void deleteOldData() {
        deleteFolder(new File(wd, "data/"));
    }

    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) { //some JVMs return null for empty dirs
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
}
